package com.agriculture.controller;

import com.agriculture.common.Response;
import com.agriculture.domain.Order;
import com.agriculture.domain.OrderItem;
import com.agriculture.service.OrderService;
import com.agriculture.dto.Order.OrderStatusUpdateRequest;
import com.agriculture.dto.Order.OrderCancelRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody Order order) {
        try {
            if (order.getOrderType() == null) {
                return ResponseEntity.badRequest().body("订单类型不能为空");
            }
            
            String orderType = order.getOrderType().toLowerCase();
            if (!orderType.equals("purchase") && !orderType.equals("sales")) {
                return ResponseEntity.badRequest().body("无效的订单类型，必须是 purchase 或 sales");
            }
            
            return ResponseEntity.ok(orderService.createOrder(order));
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            return ResponseEntity.badRequest().body(Response.error("创建订单失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{orderId}/status")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable Long orderId,
            @RequestParam String status,
            @RequestParam(required = false) String operator,
            @RequestParam(required = false) String notes) {
        
        logger.info("Updating order status - OrderId: {}, Status: {}, Operator: {}, Notes: {}", 
                 orderId, status, operator, notes);
        
        try {
            if (orderId == null) {
                return ResponseEntity.badRequest().body("订单ID不能为空");
            }
            
            OrderStatusUpdateRequest request = new OrderStatusUpdateRequest();
            request.setStatus(status);
            request.setOperator(operator != null ? operator : "system");
            request.setNotes(notes != null ? notes : "");
            
            Order updatedOrder = orderService.updateOrderStatus(orderId, request);
            return ResponseEntity.ok(Response.success("更新成功", updatedOrder));
        } catch (Exception e) {
            logger.error("Failed to update order status", e);
            return ResponseEntity.badRequest().body(Response.error("更新失败: " + e.getMessage()));
        }
    }

    @GetMapping("/buyer/{buyerId}")
    public ResponseEntity<?> getBuyerOrders(
            @PathVariable Long buyerId,
            @RequestParam(defaultValue = "purchase") String orderType) {
        return ResponseEntity.ok(orderService.getOrdersByBuyer(buyerId, orderType));
    }

    @GetMapping("/seller/{sellerId}")
    public ResponseEntity<?> getSellerOrders(
            @PathVariable Long sellerId,
            @RequestParam(defaultValue = "purchase") String orderType) {
        return ResponseEntity.ok(orderService.getOrdersBySeller(sellerId, orderType));
    }

    @PutMapping("/{orderId}/logistics")
    public ResponseEntity<?> updateLogistics(
            @PathVariable Long orderId,
            @RequestParam String logisticsNo) {
        orderService.updateLogistics(orderId, logisticsNo);
        return ResponseEntity.ok().build();
    }

    @GetMapping("")
    public Response<?> getOrders(
            @RequestParam(defaultValue = "purchase") String orderType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            int offset = (page - 1) * pageSize;
            List<Order> orders;
            int total;

            logger.info("请求参数: orderType={}, role={}, status={}, userId={}, keyword={}", 
                       orderType, role, status, userId, keyword);

            if ("purchase".equals(orderType)) {
                // 采购订单逻辑
                switch (role.toLowerCase()) {
                    case "admin":
                        // 管理员可以看到所有采购订单
                        orders = orderService.getBuyOrders("ADMIN", status, keyword, null, null, offset, pageSize);
                        total = orderService.countBuyOrders("ADMIN", status, keyword, null, null);
                        break;
                        
                    case "farmer":
                        // 农户只能看到自己作为卖家的采购订单
                        orders = orderService.getBuyOrders("FARMER", status, keyword, null, userId, offset, pageSize);
                        total = orderService.countBuyOrders("FARMER", status, keyword, null, userId);
                        break;
                        
                    case "dealer":
                        // 经销商只能看到自己作为买家的采购订单
                        orders = orderService.getBuyOrders("DEALER", status, keyword, userId, null, offset, pageSize);
                        total = orderService.countBuyOrders("DEALER", status, keyword, userId, null);
                        break;
                        
                    default:
                        return Response.error("无效的用户角色: " + role);
                }
            } else if ("sales".equals(orderType)) {
                // 销售订单逻辑
                Long sellerId = null;
                Long buyerId = null;
                
                if ("dealer".equals(role)) {
                    sellerId = userId;  // 经销商是卖家
                } else if ("consumer".equals(role)) {
                    buyerId = userId;   // 消费者是买家
                }
                
                logger.info("查询销售订单: role={}, sellerId={}, buyerId={}", role, sellerId, buyerId);
                
                orders = orderService.getSellOrders(role.toUpperCase(), status, keyword, sellerId, buyerId, offset, pageSize);
                total = orderService.countSellOrders(role.toUpperCase(), status, keyword, sellerId, buyerId);
                
                logger.info("查询结果: orders.size={}, total={}", orders.size(), total);
                
                Map<String, Object> data = new HashMap<>();
                data.put("items", orders);
                data.put("total", total);
                
                return Response.success("获取成功", data);
            } else {
                return Response.error("无效的订单类型: " + orderType);
            }

            if (orders != null) {
                orders.forEach(order -> {
                    logger.debug("Order details - ID: {}, Type: {}, Status: {}, BuyerId: {}, SellerId: {}, Amount: {}", 
                        order.getOrderId(), 
                        order.getOrderType(),
                        order.getStatus(),
                        order.getBuyerId(),
                        order.getSellerId(),
                        order.getTotalAmount());
                    
                    if (order.getOrderItems() == null) {
                        order.setOrderItems(new ArrayList<>());
                    }
                });
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", orders);
            data.put("total", total);
            
            logger.debug("Response data: {}", data);
            
            return Response.success("获取成功", data);
        } catch (Exception e) {
            logger.error("获取订单列表失败", e);
            return Response.error("获取订单列表失败: " + e.getMessage());
        }
    }

    @PutMapping("/{orderId}/cancel")
    public Response<?> cancelOrder(
        @PathVariable("orderId") Long orderId,
        @RequestParam("reason") String reason,
        @RequestParam("cancelledBy") String cancelledBy
    ) {
        try {
            OrderCancelRequest request = new OrderCancelRequest();
            request.setReason(reason);
            request.setCancelledBy(cancelledBy);

            orderService.cancelOrder(orderId, request);
            return Response.success("订单取消成功", null);
        } catch (Exception e) {
            logger.error("取消订单失败", e);
            return Response.error(e.getMessage());
        }
    }

    @GetMapping("/completedOrder")
    public Response<?> getCompletedOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam String role,
            @RequestParam(required = false) Long buyerId) {
        try {
            int offset = (page - 1) * pageSize;
            
            List<Order> orders = orderService.selectCompletedBuyOrders(
                "purchase", 
                "completed",
                null,
                buyerId,
                null,
                offset, 
                pageSize
            );
            
            int total = orderService.countCompletedBuyOrders(
                "purchase", 
                "completed",
                null,
                buyerId,
                null
            );
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", orders);
            data.put("total", total);
            
            return Response.success("获取成功", data);
        } catch (Exception e) {
            logger.error("获取已完成订单列表失败", e);
            return Response.error("获取已完成订单列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/{orderId}")
    public Response<?> getOrderDetail(@PathVariable Long orderId) {
        try {
            logger.info("获取订单详情 - orderId: {}", orderId);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null) {
                return Response.error("订单不存在");
            }
            
            return Response.success("获取成功", order);
        } catch (Exception e) {
            logger.error("获取订单详情失败", e);
            return Response.error("获取订单详情失败: " + e.getMessage());
        }
    }

    @PutMapping("/{orderId}/ship")
    public Response<?> confirmShipment(
        @PathVariable Long orderId,
        @RequestBody Map<String, String> request
    ) {
        try {
            logger.info("确认发货 - orderId: {}, request: {}", orderId, request);
            
            // 验证请求参数
            if (orderId == null) {
                return Response.error("订单ID不能为空");
            }
            
            String trackingNumber = request.get("tracking_number");
            if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
                return Response.error("物流单号不能为空");
            }
            
            // 创建状态更新请求
            OrderStatusUpdateRequest statusUpdate = new OrderStatusUpdateRequest();
            statusUpdate.setStatus("pending_receipt"); // 更新状态为待收货
            statusUpdate.setOperator(request.get("operator"));
            statusUpdate.setNotes(request.get("notes"));
            
            // 更新订单状态和物流信息
            Order updatedOrder = orderService.confirmShipment(orderId, trackingNumber, statusUpdate);
            
            return Response.success("发货成功", updatedOrder);
        } catch (Exception e) {
            logger.error("确认发货失败", e);
            return Response.error("确认发货失败: " + e.getMessage());
        }
    }
} 